import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import { Card, message, Button, Modal } from 'antd';
import PropTypes from 'prop-types';
import PateoTable from '@/components/common/PateoTable';
import PateoSearchForm from '@/components/common/PateoSearchForm';
import PateoAuthButtons from '@/components/common/PateoAuthButtons';
import styles from '@/components/common/PateoTable/TableList.less';
import HandleModel from './handleModel';
import BindModal from './bindModel';
import { filterAuth } from '@/support/common';
import BatchBindModal from './batchBindModal';
import BindDetailModal from './bindDetailModal';
import MaskText from '@/components/MaskText';

const mapStateToProps = (state: any) => ({
  FleetMng: state.FleetMng,
  loading: state.loading.models['FleetMng'],
  permissions: state?.menu?.permissions,
  user: state?.menu?.userProfile,
});
class FleetMng extends PureComponent<any, any> {
  static contextTypes = {
    permissions: PropTypes.array,
    dicData: PropTypes.array,
  };

  constructor(props: any) {
    super(props);
    this.state = {
      formValues: {},
      modalVisible: false,
      formData: {},
      bindVisible: false,
      batchBindVisible: false,
      bindDetailVisible: false,
      delModalVisible: false,
      delModalLoading: false,
    };
  }

  componentDidMount() {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'FleetMng/getFetchPage',
      payload: {
        url: '/msalcohollock/fleet/page',
        ...formValues,
      },
    });
  }
  handleFormReset = (fields: any) => {
    this.setState({
      formValues: {},
    });
  };
  //  新增
  handleAdd = () => {
    this.setState({
      modalVisible: true,
      formData: {},
    });
  };

  //  编辑
  handleEdit = (data: any) => {
    this.setState({
      modalVisible: true,
      formData: {
        ...data,
      },
    });
  };
  closeModal = () => {
    this.setState({
      modalVisible: false,
      formData: {},
    });
  };
  //关联车辆
  handleBind = (data: any) => {
    this.setState({
      bindVisible: true,
      formData: {
        ...data,
      },
    });
  };
  closedBind = () => {
    this.setState({
      bindVisible: false,
      formData: {},
    });
  };
  handleBatchBind = (data: any) => {
    this.setState({
      batchBindVisible: true,
      formData: {
        ...data,
      },
    });
  };
  closeBatchModal = () => {
    this.setState({
      batchBindVisible: false,
      formData: {},
    });
  };
  handleFreshPage = () => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    dispatch({
      type: 'FleetMng/getFetchPage',
      payload: {
        url: '/msalcohollock/fleet/page',
        ...formValues,
      },
    });
  };
  //查看关联车辆详情
  handleDetial = (data: any) => {
    this.setState({
      bindDetailVisible: true,
      formData: {
        ...data,
      },
    });
  };
  closedBindDetail = () => {
    this.setState({
      bindDetailVisible: false,
      formData: {},
    });
  };
  //  删除
  handleDelete = (record: any) => {
    const { dispatch } = this.props;
    const { formData } = this.state;
    this.setState({ delModalLoading: true });
    return dispatch({
      type: 'FleetMng/delData',
      payload: { url: `/msalcohollock/fleet/${formData.sid}` },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('删除成功');
          this.setState({ delModalVisible: false });
          this.handleFreshPage();
        } else {
          message.success(`删除失败, ${res.statusMessage}`);
        }
      },
    }).finally(() => this.setState({ delModalLoading: false }));
  };
  cloleDelModal = () => {
    this.setState({ delModalVisible: false });
  };
  render() {
    const {
      FleetMng: {
        pageData: { list, pagination },
      },
      loading,
      permissions,
      location: { pathname = '/' },
    } = this.props;
    const {
      formValues,
      modalVisible,
      formData,
      bindVisible,
      batchBindVisible,
      bindDetailVisible,
      delModalVisible,
      delModalLoading,
    } = this.state;
    // const burningStatus = getDictOptionsByCode(this.context.dicData, 'burningStatus')
    // const list = [{sid:1,name:'嘻嘻车队',contactName:'嘻嘻',contactPhoneNumber:'1111111111', tenantName:'zzz', tenantSid:1,administrator:'hhh',vehicleCount:10},
    // {sid:2,name:'哈哈车队',contactName:'哈哈',contactPhoneNumber:'22222222222', tenantName:'zzz', tenantSid:1,administrator:'hhh',vehicleCount:20}]
    const page = {
      current: pagination.pageNo || 1,
      pageSize: pagination.pageSize,
      total: pagination.totalSize,
    };

    const searchItems = [
      {
        title: '车队名称',
        type: 'input',
        key: 'name',
        maxLength: 50,
        rules: [
          {
            required: false,
            // message: '请输入中英文及数字、特殊字符!',
            // pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s\w]+$/,
            message: '不能输入空字符!',
            pattern: /^\S+$/,
          },
        ],
      },
      {
        title: '车队联系人',
        type: 'input',
        key: 'contactName',
        maxLength: 50,
        rules: [
          {
            required: false,
            // message: '请输入中英文及数字、特殊字符!',
            // pattern: /^[\u4e00-\u9fa5a-zA-Z0-9\s\w]+$/,
            message: '不能输入空字符!',
            pattern: /^\S+$/,
          },
        ],
      },
    ];

    const paginationProps = {
      showSizeChanger: true,
      showQuickJumper: true,
      ...page,
      showTotal: () => <span>共&nbsp;{page?.total}&nbsp;条</span>,
    };

    const columns = [
      {
        title: '车队名称',
        dataIndex: 'name',
      },
      {
        title: '车队联系人',
        dataIndex: 'contactName',
      },
      {
        title: '联系方式',
        dataIndex: 'contactPhoneNumber',
        render(val: any) {
          return <MaskText text={val} type="phone" />;
        },
      },
      {
        title: '关联租户',
        dataIndex: 'tenantName',
      },
      {
        title: '租户编码',
        dataIndex: 'tenantSid',
      },
      {
        title: '租户管理员账号',
        dataIndex: 'administrator',
      },
      {
        title: '关联车辆数',
        dataIndex: 'vehicleCount',
        render: (text: any, record: any) => {
          return (
            <a
              onClick={() => {
                this.handleDetial(record);
              }}
            >
              <div>{text}</div>
            </a>
          );
        },
      },
      {
        title: '操作',
        dataIndex: 'opt',
        width: 150,
        fixed: 'right',
        render: (text: any, record: any) => {
          const btns = [
            {
              title: '关联车辆',
              key: 'bind',
              auth: 'fleetMng_doRelated',
              onConfirm: () => {
                this.handleBind(record);
              },
            },
            {
              title: '批量关联',
              key: 'binds',
              auth: 'fleetMng_doBatchRelated',
              onConfirm: () => {
                this.handleBatchBind(record);
              },
            },
            {
              title: '编辑',
              key: 'edit',
              auth: 'fleetMng_doEdit',
              onConfirm: () => {
                this.handleEdit(record);
              },
            },
            {
              title: '删除',
              key: 'del',
              auth: 'fleetMng_doDel',
              // message: '是否确认删除？',
              // Popconfirm: true,
              onConfirm: () => {
                this.setState({
                  delModalVisible: true,
                });
              },
            },
          ];
          return <PateoAuthButtons btns={btns} max={4} pathname={pathname} />;
        },
      },
    ];

    const tableProps = {
      key: 'sid',
      columns,
      dataSource: list,
      loading,
      pagination: paginationProps,
      scroll: { x: 'max-content' },
      onRow: (record: any) => ({ onClick: () => this.setState({ formData: record }) }),
    };
    return (
      <div>
        <Card bordered={false}>
          <PateoSearchForm
            onRef={(val: any) => (this.searchForm = val)}
            searchItems={searchItems}
            fetchParams={{
              type: 'FleetMng/getFetchPage',
              url: '/msalcohollock/fleet/page',
              extraArgs: {},
            }}
            saveFormValues={(val: any) => {
              this.setState({
                formValues: Object.assign(this.state.formValues, val),
              });
            }}
            handleFormReset={this.handleFormReset}
          />
        </Card>
        <Card className={styles.standardTable}>
          <div className="my_newItem">
            {filterAuth('fleetMng_doAdd', permissions, pathname) ? (
              <Button size="small" type="primary" onClick={this.handleAdd}>
                新增车队
              </Button>
            ) : null}
          </div>
          <PateoTable
            extraHandle={true}
            currentName={'page'}
            pageSizeName={'size'}
            tableProps={tableProps}
            fetchParams={{ type: 'FleetMng/getFetchPage', url: '/msalcohollock/fleet/page' }}
            formValues={formValues}
          />
        </Card>
        <HandleModel
          modalVisible={modalVisible}
          formData={formData}
          closeModal={this.closeModal}
          freshPage={this.handleFreshPage}
        ></HandleModel>
        <BindModal
          modalVisible={bindVisible}
          closeModal={this.closedBind}
          freshPage={this.handleFreshPage}
          formData={formData}
        ></BindModal>
        <BatchBindModal
          modalVisible={batchBindVisible}
          closeModal={this.closeBatchModal}
          freshPage={this.handleFreshPage}
          formData={formData}
        ></BatchBindModal>
        <BindDetailModal
          modalVisible={bindDetailVisible}
          closeModal={this.closedBindDetail}
          freshPage={this.handleFreshPage}
          formData={formData}
        ></BindDetailModal>
        <Modal
          title={'删除车队'}
          okButtonProps={{ size: 'small' }}
          cancelButtonProps={{ size: 'small' }}
          centered
          visible={delModalVisible}
          confirmLoading={delModalLoading}
          onOk={this.handleDelete}
          onCancel={this.cloleDelModal}
        >
          <div style={{ textAlign: 'center' }}>{`确定要删除车队"${formData.name}"吗?`}</div>
        </Modal>
      </div>
    );
  }
}
export default connect(mapStateToProps)(FleetMng);
